import { reactive, computed } from 'vue'
import { productAPI, reservationAPI } from '../api/index.js'

// 预定状态枚举
const RESERVATION_STATUS = {
  PENDING: 'pending',     // 待确认
  CONFIRMED: 'confirmed', // 已确认
  CANCELLED: 'cancelled', // 已取消
  COMPLETED: 'completed'  // 已完成
}

// 全局状态管理
const state = reactive({
  // 商品列表（从后端获取）
  products: [],

  // 用户预定记录（从后端获取）
  reservations: [],

  // 当前用户信息
  currentUser: {
    id: 1,
    name: '用户',
    phone: '',
    address: ''
  },

  // 当前页面
  currentPage: 'products', // products, reservations

  // 加载状态
  loading: {
    products: false,
    reservations: false
  }
})

// 计算属性
const getters = {
  // 获取所有有库存的商品
  availableProducts: computed(() => 
    state.products.filter(product => product.stock > 0)
  ),
  
  // 获取用户的预定记录
  userReservations: computed(() => 
    state.reservations.filter(reservation => reservation.userId === state.currentUser.id)
  ),
  
  // 获取待确认的预定数量
  pendingReservationsCount: computed(() => 
    state.reservations.filter(r => r.status === RESERVATION_STATUS.PENDING).length
  ),
  
  // 获取已确认的预定数量
  confirmedReservationsCount: computed(() => 
    state.reservations.filter(r => r.status === RESERVATION_STATUS.CONFIRMED).length
  )
}

// 操作方法
const actions = {
  // 加载商品列表
  async loadProducts() {
    try {
      state.loading.products = true
      const products = await productAPI.getAllProducts()
      state.products = products
      return products
    } catch (error) {
      console.error('加载商品列表失败:', error)
      throw error
    } finally {
      state.loading.products = false
    }
  },

  // 加载用户预定记录
  async loadUserReservations(userId = state.currentUser.id) {
    try {
      state.loading.reservations = true
      const reservations = await reservationAPI.getUserReservations(userId)
      state.reservations = reservations
      return reservations
    } catch (error) {
      console.error('加载预定记录失败:', error)
      throw error
    } finally {
      state.loading.reservations = false
    }
  },

  // 创建预定
  async createReservation(productId, quantity, userInfo) {
    try {
      // 验证数量有效
      if (quantity <= 0) {
        throw new Error('预定数量必须大于0')
      }

      // 验证用户信息
      if (!userInfo.name || !userInfo.phone || !userInfo.address) {
        throw new Error('请填写完整的联系信息')
      }

      // 构建请求数据
      const reservationData = {
        userId: state.currentUser.id,
        productId: productId,
        quantity: quantity,
        contactName: userInfo.name,
        contactPhone: userInfo.phone,
        contactAddress: userInfo.address,
        notes: userInfo.notes || ''
      }

      // 调用后端API创建预定
      const reservation = await reservationAPI.createReservation(reservationData)

      // 更新本地状态
      state.reservations.unshift(reservation)

      // 更新商品库存
      const product = state.products.find(p => p.id === productId)
      if (product) {
        product.stock -= quantity
      }

      return reservation
    } catch (error) {
      console.error('创建预定失败:', error)
      throw error
    }
  },

  // 确认预定
  async confirmReservation(reservationId) {
    try {
      const reservation = await reservationAPI.confirmReservation(reservationId)

      // 更新本地状态
      const index = state.reservations.findIndex(r => r.id === reservationId)
      if (index !== -1) {
        state.reservations[index] = reservation
      }

      return reservation
    } catch (error) {
      console.error('确认预定失败:', error)
      throw error
    }
  },

  // 取消预定（释放库存）
  async cancelReservation(reservationId) {
    try {
      const reservation = await reservationAPI.cancelReservation(reservationId)

      // 更新本地状态
      const index = state.reservations.findIndex(r => r.id === reservationId)
      if (index !== -1) {
        const oldReservation = state.reservations[index]
        state.reservations[index] = reservation

        // 恢复库存
        if (oldReservation.status !== RESERVATION_STATUS.CANCELLED) {
          const product = state.products.find(p => p.id === oldReservation.productId)
          if (product) {
            product.stock += oldReservation.quantity
          }
        }
      }

      return reservation
    } catch (error) {
      console.error('取消预定失败:', error)
      throw error
    }
  },

  // 完成预定
  async completeReservation(reservationId) {
    try {
      const reservation = await reservationAPI.completeReservation(reservationId)

      // 更新本地状态
      const index = state.reservations.findIndex(r => r.id === reservationId)
      if (index !== -1) {
        state.reservations[index] = reservation
      }

      return reservation
    } catch (error) {
      console.error('完成预定失败:', error)
      throw error
    }
  },

  // 切换页面
  setCurrentPage(page) {
    state.currentPage = page
  },

  // 更新用户信息
  updateUserInfo(userInfo) {
    Object.assign(state.currentUser, userInfo)
  },

  // 刷新商品数据
  async refreshProducts() {
    return await this.loadProducts()
  },

  // 刷新预定数据
  async refreshReservations() {
    return await this.loadUserReservations()
  },

  // 初始化数据
  async initializeData() {
    try {
      await Promise.all([
        this.loadProducts(),
        this.loadUserReservations()
      ])
    } catch (error) {
      console.error('初始化数据失败:', error)
      throw error
    }
  }
}

// 导出状态和方法
export { state, actions, getters, RESERVATION_STATUS }
